package com.example.beatbox.view

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.beatbox.R
import com.example.beatbox.databinding.FragmentBeatBoxBinding
import com.example.beatbox.databinding.ListItemSoundBinding
import com.example.beatbox.model.BeatBox
import com.example.beatbox.model.Sound
import com.example.beatbox.model.SoundViewModel

class BeatBoxFragment : Fragment() {

    private lateinit var mBeatBox: BeatBox

    companion object {
        fun newInstance() = BeatBoxFragment()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        retainInstance = true
        mBeatBox = BeatBox(activity!!)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val binding: FragmentBeatBoxBinding =
            DataBindingUtil.inflate(inflater, R.layout.fragment_beat_box, container, false)
        binding.recyclerView.layoutManager = GridLayoutManager(activity, 3)
        binding.recyclerView.adapter = SoundAdapter(mBeatBox.sounds)
        return binding.root
    }

    inner class SoundHolder(private var mBinding: ListItemSoundBinding) :
        RecyclerView.ViewHolder(mBinding.root) {
        init {
            mBinding.viewModel = SoundViewModel(mBeatBox)
        }

        fun bind(sound: Sound) {
            mBinding.viewModel!!.sound = sound
            mBinding.executePendingBindings()
        }
    }

    inner class SoundAdapter(private val mSounds: List<Sound>) :
        RecyclerView.Adapter<SoundHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SoundHolder {
            val inflater = LayoutInflater.from(activity)
            val binding = DataBindingUtil.inflate<ListItemSoundBinding>(
                inflater,
                R.layout.list_item_sound,
                parent,
                false
            )
            return SoundHolder(binding)
        }

        override fun getItemCount(): Int {
            return mSounds.size
        }

        override fun onBindViewHolder(holder: SoundHolder, position: Int) {
            val sound = mSounds[position]
            holder.bind(sound)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mBeatBox.release()
    }
}